< previous page page_152 next page >

Page 152
Scoping Out the Variables
By now you probably have noticed that a Visual Basic application has different types of source files that contain the program instructions that make up your application. These files, such as forms, code, and class modules, often contain multiple procedures. A form module might have event procedures for each control on the form. In addition, the form modules might contain general routines that are used by several of the event procedures. The standard code modules can also contain multiple procedures. These procedures might be in the form of functions or subroutines.
When a module contains multiple routines, those routines often must share data between them. Creating a variable in one routine with a Dim statement does not automatically make that variable available to any of the other routines. To understand how to use variables properly, you must first understand how variables can be defined in your application. Declaring variables simply means that the application knows that the variable exists and what values or type of data is valid for that variable. Also, how a variable is defined affects how its data can be shared within the application.
Defining the Variables
If the only routines a form module contains are the event procedures, then you would not have to worry about sharing data. As you have seen in many of the sample projects you have created, all modules, including form modules, have a Declarations section that contains the definitions for many of the variables your application is using. You can view this section by selecting General from the Object drop-down list and Declarations from the Procedure drop-down list in the Code Editor (see Figure 6.1).
With only event procedures, you would have no need to declare any variables. Any variables that you declare are generally used to store data temporarily to use when performing calculations within the application. For example, you might want to calculate several values, compare them, and then perform some operations on them, depending on the result of the comparison. You must keep the values if you want to compare them, but you don't need to store them in an object property.
Besides variables, you can also declare some data for your application as constants. As the name implies, these values remain constant throughout the life of the application. By using constants you can make your code more readable by providing meaningful names instead of numbers or hard-coded strings. In fact, you have been using constants, even if you haven't realized it. When you code a statement like the following you are using a built-in constant:
frmNote.Visible = True

 
< previous page page_152 next page >

If you like this book, buy it!